package com.wlts.wzy.DYOrderModule.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.linkedmall.model.v20180116.CreateOrderV2Request;
import com.aliyuncs.linkedmall.model.v20180116.CreateOrderV2Response;
import com.aliyuncs.linkedmall.model.v20180116.EnableOrderResponse;
import com.wlts.wzy.Base.BaseEntity;
import com.wlts.wzy.DYGoodsModule.DYapi.DySdk;
import com.wlts.wzy.DYOrderModule.entity.DyOrders;
import com.wlts.wzy.DYOrderModule.service.IDyOrdersService;
import com.wlts.wzy.DYUserModule.entity.DyOauth;
import com.wlts.wzy.DYUserModule.entity.DyStoreUser;
import com.wlts.wzy.DYUserModule.service.IDyStoreUserService;
import com.wlts.wzy.LMGoodsModule.entity.LmAddress;
import com.wlts.wzy.LMGoodsModule.entity.LmSelfGoods;
import com.wlts.wzy.LMGoodsModule.service.ILmAddressService;
import com.wlts.wzy.LMGoodsModule.service.ILmSelfGoodsService;
import com.wlts.wzy.Result.Result;
import com.wlts.wzy.api.request.dy.DyOrderAddress;
import com.wlts.wzy.api.request.dy.PageOrderToDyApiRequest;
import com.wlts.wzy.api.request.ks.IdsRequest;
import com.wlts.wzy.api.response.dy.UpdateDyOrdersResponse;
import com.wlts.wzy.api.vo.DeliveryAddress;
import com.wlts.wzy.api.vo.DyVo.ExpressName;
import com.wlts.wzy.configBean.DyConfig.DyConfig;
import com.wlts.wzy.configBean.LmConfig.LmConfig;
import com.wlts.wzy.expand.MyLambdaQueryWrapper;
import com.wlts.wzy.util.AddressResolutionUtil;
import com.wlts.wzy.util.CopyUtils;
import com.wlts.wzy.util.StringUtils;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.wlts.wzy.KSOrderModule.util.PutOrdersToLmUtil.enableOrder;
import static com.wlts.wzy.configBean.LmConfig.LmConfig.client;

/**
 * <p>
 * 快手订单表 前端控制器
 * </p>
 *
 * @author zhiyong
 * @since 2021-02-28
 */
@RestController
@RequestMapping("/test/dy-orders")
public class TestDyOrdersController {
    @Autowired
    private DyConfig dyConfig;
    @Autowired
    private IDyStoreUserService dyStoreUserService;
    @Autowired
    private IDyOrdersService dyOrdersService;
    @Autowired
    private ILmSelfGoodsService lmSelfGoodsService;
    @Autowired
    private ILmAddressService lmAddressService;

    @ApiOperation(value = "获得测试抖音订单")
    @RequestMapping(value = "getOrdersDyTest", method = RequestMethod.POST)
    public Result getOrdersDyTest() {

        DyStoreUser dyStoreUser = dyConfig.getDyStoreUserConfig();

        DyOauth ksOauth = dyStoreUser.getDyOauth();

        if (ksOauth == null) {
            return Result.buildResult(500, "账号未授权");
        }


        PageOrderToDyApiRequest orderListRequest = new PageOrderToDyApiRequest();

        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime time = LocalDateTime.now();

        orderListRequest.setOrder_status(101 + "");
        orderListRequest.setStart_time(df.format(time.minusDays(1)));
        orderListRequest.setEnd_time(df.format(time));
        orderListRequest.setIs_desc(1 + "");
        orderListRequest.setOrder_by("update_time");

        int page = 0;

        //    List<UpdateDyOrdersResponse> responseList =  DySdk.orderList(dyStoreUser.getAppKey(), dyStoreUser.getAppSecret(), ksOauth.getAccessToken(), orderListRequest);

        while (true) {
            orderListRequest.setPage(page + "");
            orderListRequest.setSize(100 + "");

            List<UpdateDyOrdersResponse> responseList = DySdk.orderList(dyStoreUser.getAppKey(), dyStoreUser.getAppSecret(), ksOauth.getAccessToken(), orderListRequest);

            List<DyOrders> ksOrdersList = responseList.stream().map(a -> {
                MyLambdaQueryWrapper<DyOrders> orderWrapper = new MyLambdaQueryWrapper<>();
                orderWrapper.eq(DyOrders::getOrderId, a.getOrderId());
                orderWrapper.eq(DyOrders::getDelFlag, "0");
                DyOrders orders = dyOrdersService.getOne(orderWrapper);

                if (orders == null) {
                    orders = new DyOrders();
                }
                CopyUtils.copyProperties(a, orders);
                dyOrdersService.saveOrUpdate(orders);
                return orders;
            }).collect(Collectors.toList());
//            if (ksOrdersList.size() > 0) {
//                dyOrdersService.saveOrUpdateBatch(ksOrdersList);
//            }
            page += 1;

            if (responseList.size() < 100) {
                break;
            }

        }
        return Result.buildResult();

    }

    @ApiOperation(value = "获得测试抖音快递代码")
    @RequestMapping(value = "getExpressDyTest", method = RequestMethod.POST)
    public Result getExpressDyTest() {



        return Result.buildResult();

    }


    @ApiOperation(value = "抖音小批量补推订单")
    @RequestMapping(value = "putOrderToLm", method = RequestMethod.POST)
    public Result putOrderToLm(@RequestBody List<String> orderId) {

        //       System.out.println(requests);

        MyLambdaQueryWrapper<DyOrders> queryWrapper = new MyLambdaQueryWrapper<>();
        queryWrapper.eq(BaseEntity::getDelFlag, "0");
        queryWrapper.in(DyOrders::getOrderId, orderId);

        List<DyOrders> ordersList = dyOrdersService.list(queryWrapper);

        List<String> failOrder = new ArrayList<>();

        putDyOrderToLm(failOrder, ordersList);

        if (failOrder.size() > 0) {
            return Result.buildResult(500, "推送失败的订单订单：" + JSON.toJSONString(failOrder));
        }
        return Result.buildResult();
    }

    private void putDyOrderToLm(List<String> failOrder, List<DyOrders> ordersList) {
        ordersList.forEach(ksOrders -> {

//[{"buyerId":0,"createTime":1612605117278,"discountFee":0,"id":8283462433580,"itemId":943491185290,"itemLinkUrl":"https://app.kwaixiaodian.com/merchant/shop/detail?id=943491185290&hyId=kwaishop&layoutType=4","itemPicUrl":"https://ali-ec.static.yximgs.com/ufile/adsocial/87243885-9d23-45e8-bd5d-d15dac7df6c0.jpg","itemTitle":"【瑜大直播】艺品赞红豆薏米茶150g*1袋","itemType":1,"num":1,"oid":2103700006986580,"originalPrice":990,"price":990,"refundId":2103700007004580,"refundList":[{"refundId":2103700007004580,"refundStatus":10}],"refundStatus":10,"relItemId":1612577579226,"relSkuId":0,"skuDesc":"红豆薏米茶","skuId":943491186290,"updateTime":1612605117278}]


            MyLambdaQueryWrapper<LmSelfGoods> selfGoodsWrapper = new MyLambdaQueryWrapper<>();

            selfGoodsWrapper.eq(LmSelfGoods::getRelItemId, ksOrders.getOutProductId());

            LmSelfGoods lmSelfGoods = lmSelfGoodsService.getOne(selfGoodsWrapper);

            if (lmSelfGoods != null) {
                //    if(ksOrders.getStatus()==30){
                CreateOrderV2Request request = new CreateOrderV2Request();
                CreateOrderV2Request.ItemList itemList = new CreateOrderV2Request.ItemList();
                DeliveryAddress deliveryAddress = new DeliveryAddress();
                request.setBizId(LmConfig.LZ_BIZ_ID);
                request.setAccountType("ANONY");
                request.setThirdPartyUserId(ksOrders.getShopId() + "");
                request.setBizUid(request.getThirdPartyUserId());

                List<CreateOrderV2Request.ItemList> itemLists = new ArrayList<>();

                //request.setOutTradeId(ksOrders.getOrderId() + "");

                String outTradeId=ksOrders.getOrderId() + "";

                outTradeId = outTradeId.substring(0,outTradeId.length()-1);

                System.out.println("订单号"+outTradeId);

                request.setOutTradeId(outTradeId);

                itemList.setLmItemId(lmSelfGoods.getLmItemId() + "");
                itemList.setQuantity(ksOrders.getComboNum()-1);

                System.out.println("数量"+itemList.getQuantity());

                if (ksOrders.getOutSkuId() != 0) {
                    itemList.setSkuId(ksOrders.getOutSkuId());
                } else {
                    if (ksOrders.getCode() != null) {
                        itemList.setSkuId(Long.valueOf(ksOrders.getCode()));
                    }
                }


                DyOrderAddress ksOrdersAddress = JSONObject.parseObject(ksOrders.getPostAddr(), DyOrderAddress.class);

                /**
                 * 设置地址
                 */
                deliveryAddress.setFullName(ksOrders.getPostReceiver());
                deliveryAddress.setMobile(ksOrders.getPostTel());
                // deliveryAddress.setAddressDetail(ksOrdersAddress.getProvince().getName() + ksOrdersAddress.getCity().getName() + ksOrdersAddress.getTown().getName() + ksOrdersAddress.getDetail());
                deliveryAddress.setAddressDetail(ksOrdersAddress.getDetail());
                MyLambdaQueryWrapper<LmAddress> provinceWrapper = new MyLambdaQueryWrapper<>();

                provinceWrapper.like(LmAddress::getDivisionName, ksOrdersAddress.getProvince().getName());

                provinceWrapper.eq(LmAddress::getParentId, 1);

                LmAddress province = lmAddressService.getOne(provinceWrapper);

                if (province == null) {
                    MyLambdaQueryWrapper<LmAddress> provinceWrapper2 = new MyLambdaQueryWrapper<>();

                    provinceWrapper2.like(LmAddress::getDivisionName, ksOrdersAddress.getProvince().getName().replace("市", ""));

                    provinceWrapper2.eq(LmAddress::getParentId, 1);
                    province = lmAddressService.getOne(provinceWrapper2);
                }

                if (province != null) {
                    MyLambdaQueryWrapper<LmAddress> cityWrapper = new MyLambdaQueryWrapper<>();

                    cityWrapper.like(LmAddress::getDivisionName, ksOrdersAddress.getCity().getName());

                    cityWrapper.eq(LmAddress::getParentId, province.getDivisionCode());

                    LmAddress city = lmAddressService.getOne(cityWrapper);

                    boolean jump = false;

                    if (city == null) {
                        if (ksOrdersAddress.getCity().getName().equals("市辖区") || ksOrdersAddress.getCity().getName().equals("县")) {

                            MyLambdaQueryWrapper<LmAddress> cityWrapper1 = new MyLambdaQueryWrapper<>();

                            cityWrapper1.like(LmAddress::getDivisionName, ksOrdersAddress.getProvince().getName());

                            cityWrapper1.eq(LmAddress::getParentId, province.getDivisionCode());

                            city = lmAddressService.getOne(cityWrapper1);
                        } else {
                            if (ksOrdersAddress.getCity().getName().equals("自治区直辖县级行政区划") || ksOrdersAddress.getCity().getName().equals("省直辖县级行政区划")) {
                                jump = true;
                            }
                        }
                    }
                    if (city == null && !jump) {
                        System.out.println("系统不存在" + ksOrdersAddress.getProvince().getName() + "省下的：" + ksOrdersAddress.getCity().getName());

                    } else {
                        LmAddress dest;
                        if (jump) {
                            MyLambdaQueryWrapper<LmAddress> destWrapper = new MyLambdaQueryWrapper<>();

                            destWrapper.like(LmAddress::getDivisionName, ksOrdersAddress.getTown().getName());

                            destWrapper.eq(LmAddress::getParentId, province.getDivisionCode());

                            dest = lmAddressService.getOne(destWrapper);
                        } else {
                            MyLambdaQueryWrapper<LmAddress> destWrapper = new MyLambdaQueryWrapper<>();

                            destWrapper.like(LmAddress::getDivisionName, ksOrdersAddress.getTown().getName());

                            destWrapper.eq(LmAddress::getParentId, city.getDivisionCode());

                            dest = lmAddressService.getOne(destWrapper);
                        }

                        if (dest == null) {

                            if (jump) {
                                MyLambdaQueryWrapper<LmAddress> destWrapper1 = new MyLambdaQueryWrapper<>();

                                destWrapper1.like(LmAddress::getDivisionName, "其它区");

                                destWrapper1.eq(LmAddress::getParentId, province.getDivisionCode());

                                dest = lmAddressService.getOne(destWrapper1);
                            } else {
                                MyLambdaQueryWrapper<LmAddress> destWrapper1 = new MyLambdaQueryWrapper<>();

                                destWrapper1.like(LmAddress::getDivisionName, "其它区");

                                destWrapper1.eq(LmAddress::getParentId, city.getDivisionCode());

                                dest = lmAddressService.getOne(destWrapper1);
                            }

                            if (dest == null) {
                                System.out.println("系统不存在" + ksOrdersAddress.getProvince().getName() + "省下：" + ksOrdersAddress.getCity().getName() + "市的区：" + ksOrdersAddress.getTown().getName());

                            }


                        }

                        if (dest != null) {

                            deliveryAddress.setDivisionCode(dest.getDivisionCode() + "");

                            List<Map<String, String>> table = AddressResolutionUtil.addressResolution(ksOrdersAddress.getDetail());

                            if (table.size() > 0) {

                                String townName = table.get(0).get("town");

                                if (!StringUtils.isEmpty(townName)) {

                                    //    System.out.println("街道名字："+townName);

                                    MyLambdaQueryWrapper<LmAddress> townWrapper = new MyLambdaQueryWrapper<>();

                                    townWrapper.like(LmAddress::getDivisionName, townName);

                                    townWrapper.eq(LmAddress::getParentId, dest.getDivisionCode());

                                    LmAddress town = lmAddressService.getOne(townWrapper);

                                    if (town != null) {
                                        //    System.out.println("街道："+town.toString());
                                        deliveryAddress.setTownDivisionCode(town.getDivisionCode() + "");
                                    }
                                }
                            }

                            itemLists.add(itemList);

                            request.setItemLists(itemLists);

                            //    System.out.println("地址详细："+JSON.toJSONString(deliveryAddress));

                            request.setDeliveryAddress(JSON.toJSONString(deliveryAddress));

                            try {
                                //    System.out.println("请求内容："+JSON.toJSONString(request));
                                //创建订单
                                //   System.out.println("正在推送");

                                // System.out.println(JSON.toJSONString(request));

                                CreateOrderV2Response resp = client.getAcsResponse(request);

                                 System.out.println("创建订单报文内容：" + JSON.toJSONString(resp));


                                EnableOrderResponse enableOrderResponse = enableOrder(request.getOutTradeId(), resp.getModel().getLmOrderList().get(0).getLmOrderId(), ksOrders.getShopId() + "");

                                System.out.println("支付订单订单报文内容" + JSON.toJSONString(enableOrderResponse));

                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                          //  dyOrdersService.updateById(ksOrders);
                        } else {

                        }
                    }
                } else {
                    System.out.println("系统不存在省份：" + ksOrdersAddress.getProvince().getName());

                }
            }

        });
    }
}
